package cn.lh.product.service.impl;

import cn.lh.basic.service.IBaiduAiAuditService;
import cn.lh.org.exception.BusinessException;
import cn.lh.product.domain.Product;
import cn.lh.product.domain.ProductDetail;
import cn.lh.product.mapper.ProductDetailMapper;
import cn.lh.product.mapper.ProductMapper;
import cn.lh.product.service.IProductService;
import cn.lh.basic.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * 业务实现类：
 */
@Service
public class ProductServiceImpl extends BaseServiceImpl<Product> implements IProductService {
    @Autowired
    private ProductDetailMapper productDetailMapper;

    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private IBaiduAiAuditService baiduAiAuditService;

    @Override
    @Transactional
    public void add(Product product) {
        boolean result1 = baiduAiAuditService.textAudit(product.getName());
        String[] resources = product.getResources().split(",");
        boolean result2 = baiduAiAuditService.imgAudit(resources);
        if (result1 && result2) {
            super.add(product);
            ProductDetail productDetail = product.getProductDetail();
            productDetail.setProductId(product.getId());
            productDetailMapper.save(productDetail);
        } else {
            throw new BusinessException("数据不合法");
        }

    }

    @Override
    @Transactional
    public void update(Product product) {
        boolean result1 = baiduAiAuditService.textAudit(product.getName());
        String[] resources = product.getResources().split(",");
        boolean result2 = baiduAiAuditService.imgAudit(resources);
        if (result1 && result2){
            super.update(product);
            ProductDetail productDetail = product.getProductDetail();
            if (productDetail != null) {
                productDetailMapper.update(productDetail);
            }
        } else {
            throw new BusinessException("数据不合法");
        }
    }

    @Override
    @Transactional
    public void del(Long id) {
        super.del(id);
        productDetailMapper.removeByProductId(id);
    }

    @Override
    public void onSale(Long[] ids) {
        Date onSaleTime = new Date();
        productMapper.onSale(ids, onSaleTime);
    }

    @Override
    public void offSale(Long[] ids) {
        Date offSaleTime = new Date();
        productMapper.offSale(ids, offSaleTime);
    }

    @Override
    @Transactional
    public void batchDelete(Long[] ids) {
        for (Long id : ids) {
            del(id);
        }
    }
}
